<?xml version="1.0" encoding="UTF-8" ?>
<%@page import="messenger.domain.User"%>
<%@page import="messenger.context.Constants"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Messenger</title>
<style type="text/css">
* {
	font-size: 10pt;
	font-family: sans-serif;
}

#chatWindow {
	width: 100%;
	height: 500px;
	overflow: auto;
	text-align: left;
	border: thin;
}

.nameArea {
	font-weight: bold;
}

.messageArea {
	margin-left: 20px;
}
</style>
<script type="text/javascript" src="/cantrees/js/jquery-1.4.2.js"></script>
<script type="text/javascript">
	var uniqueUserName = '<%= ((User)session.getAttribute(Constants.USER_ATTRIBUTE)).getUniqueName() %>';
	var lastMessagesUser = '';
	var intervalReference;
	var failCount = 0;
	
	$(document).ready(function() {
		$('#messageInput').keydown( function(event){
		    if (event.keyCode == 13) {           
		        sendMessage();
		        return;                   
		    }
		});
		
		$('input:button').click(function() {
			sendMessage();
		});
		
		intervalReference = setInterval(checkNewMessage, 500);
	});
	
	var Message = function (message, uniqueUserName) {
		this.message = message;
		this.uniqueUserName = uniqueUserName;
	};
	
	function sendMessage() {
		var message = $('#messageInput').val();
		if(message != '') {
			var messageInstance = new Message(message, uniqueUserName);
			
			$.ajax({
				url: '/cantrees/message', 
				type: 'post',
				data: 'method=send&message=' + message,
				success: function(data, status){
					addMessageToChatWindow(messageInstance);
				},
				error: function(xhr, status, errorThrown){
					alert('상대방이 메시지를 받지 못했을 수 있습니다.');
				},
				complete: function(xhr, status){
				}
			});
			
			$('#messageInput').val('');
		}
	}
	
	var addedAreaHeight = 0;
	function addMessageToChatWindow(message) {
		if (lastMessagesUser != message.uniqueUserName) {
			addedAreaHeight = addedAreaHeight +
			$('<div></div>')
				.html('[' + message.uniqueUserName + ']')
				.addClass('nameArea')
				.appendTo('#chatWindow')
				.height();
		}
		
		addedAreaHeight = addedAreaHeight +
		$('<div></div>')
			.html(message.message)
			.addClass('messageArea')
			.appendTo('#chatWindow')
			.height();
			
		lastMessagesUser = message.uniqueUserName;
		
		$('#chatWindow').scrollTop($('#chatWindow').height() + addedAreaHeight);
	}
	
	function checkNewMessage() {
		$.ajax({
			url: '/cantrees/message', 
			type: 'post',
			data: 'method=check',
			dataType: 'json',
			success: function(data, status){
				if (data) {
					$.each(data, function(index, entry) {
						var messageInstance = new Message(entry['message'], entry['uniqueUserName']);
						addMessageToChatWindow(messageInstance);
					});
				}
			},
			error: function(xhr, status, errorThrown){
				if (failCount > 10) {
					alert('서버와 연결이 끊겼습니다. 다시 접속하세요.');
					clearInterval(intervalReference);
				} else {
					failCount++;
				}
			},
			complete: function(xhr, status){
			}
		});
	}
</script>
</head>
<body>
	<form action="/cantrees/message" method="post">
		<div id="chatWindow">
			<span class="nameArea">
			[공지]
			</span>
			<span class="messageArea">
			타인의 금전요구에 응하십시오.
			</span>
			<br />
		</div>
		<input type="text" name="message" id="messageInput"/>
		<input type="button" value="보내기" />
		<input type="text" style="display: none;" />
	</form>
</body>
</html>